<template>
  <div id="manageContestView">
    <a-form
      :model="searchParams"
      layout="inline"
      style="display: flex; flex-wrap: wrap"
    >
      <a-form-item field="name" label="名称" style="min-width: 240px">
        <a-input v-model="searchParams.name" placeholder="请输入名称" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="doSubmit">提交</a-button>
      </a-form-item>
      <a-form-item style="margin-left: auto">
        <a-button status="warning" @click="handleClick">新增</a-button>
        <a-modal
          v-model:visible="visible"
          title="新增用户"
          @cancel="handleCancel"
          @ok="doAdd"
        >
          <a-form :model="form" style="width: 450px">
            <a-form-item field="name" label="比赛名">
              <a-input v-model="form.name" />
            </a-form-item>
            <a-form-item field="startTime" label="比赛时间">
              <a-range-picker showTime @change="onChange" />
              <!--              <a-input v-model="form.startTime" />-->
            </a-form-item>
            <a-form-item field="length" label="进行时间（分钟）">
              <a-input v-model="form.length" disabled />
            </a-form-item>
            <a-form-item field="introduction" label="简介">
              <a-textarea
                placeholder="输入简介"
                allow-clear
                v-model="form.introduction"
              />
            </a-form-item>
            <a-form-item field="password" label="密码">
              <a-input
                placeholder="公开比赛不用设置密码"
                v-model="form.password"
              />
            </a-form-item>
            <a-form-item field="questionIds" label="题目">
              <a-select v-model="form.questionIds" multiple>
                <a-option
                  v-for="(item, index) in questionList"
                  :key="index"
                  :value="item"
                  >{{ item }}</a-option
                >
              </a-select>
            </a-form-item>
          </a-form>
        </a-modal>
        <a-popconfirm
          content="确定删除吗?"
          okText="确定"
          cancelText="取消"
          type="error"
          @ok="doBatchDelete"
        >
          <a-button status="danger" style="margin-left: 10px"
            >批量删除</a-button
          >
        </a-popconfirm>
      </a-form-item>
    </a-form>
    <a-table
      :ref="tableRef"
      :columns="columns"
      :data="dataList"
      row-key="id"
      :row-selection="rowSelection"
      v-model:selectedKeys="selectedKeys"
      :pagination="{
        showTotal: true,
        pageSize: searchParams.pageSize,
        current: searchParams.current,
        total,
      }"
      @page-change="onPageChange"
    >
      <template #optional="{ record }">
        <a-space>
          <a-button type="primary" @click="handleClick2(record)">修改</a-button>
          <a-modal
            v-model:visible="visible2"
            title="修改比赛"
            @cancel="handleCancel2"
            @ok="doUpdate"
          >
            <a-form :model="form" style="width: 450px">
              <a-form-item field="name" label="比赛名">
                <a-input v-model="form.name" />
              </a-form-item>
              <a-form-item field="startTime" label="比赛时间">
                <a-range-picker
                  v-model="updateTime"
                  showTime
                  @change="onChange"
                />
                <!--              <a-input v-model="form.startTime" />-->
              </a-form-item>
              <a-form-item field="length" label="进行时间（分钟）">
                <a-input v-model="form.length" disabled />
              </a-form-item>
              <a-form-item field="introduction" label="简介">
                <a-textarea
                  placeholder="输入简介"
                  allow-clear
                  v-model="form.introduction"
                />
              </a-form-item>
              <a-form-item field="password" label="密码">
                <a-input
                  placeholder="公开比赛不用设置密码"
                  v-model="form.password"
                />
              </a-form-item>
              <a-form-item field="questionIds" label="题目">
                <a-select v-model="form.questionIds" multiple>
                  <a-option
                    v-for="(item, index) in questionList"
                    :key="index"
                    :value="item"
                    >{{ item }}</a-option
                  >
                </a-select>
              </a-form-item>
            </a-form>
          </a-modal>
          <a-popconfirm
            content="确定删除吗?"
            okText="确定"
            cancelText="取消"
            type="error"
            @ok="doDelete(record)"
          >
            <a-button status="danger">删除</a-button>
          </a-popconfirm>
        </a-space>
      </template>
    </a-table>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watchEffect } from "vue";
import {
  Contest,
  ContestControllerService,
  ContestQueryRequest,
  Page_Question_,
  Question,
  QuestionControllerService,
  QuestionQueryRequest,
  User,
  UserControllerService,
  UserQueryRequest,
} from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import * as querystring from "querystring";
import { useRouter } from "vue-router";
import moment from "moment";

const tableRef = ref();

const dataList = ref([]);
const total = ref(0);
const searchParams = ref<ContestQueryRequest>({
  name: "",
  pageSize: 10,
  current: 1,
});
const questionList = ref([]);
const updateQuestionList = ref([]);

const updateTime = ref([]);
const selectedKeys = ref([]);
const rowSelection = reactive({
  type: "checkbox",
  showCheckedAll: true,
  onlyCurrent: false,
});

const visible = ref(false);
const visible2 = ref(false);
const form = reactive({
  id: "",
  name: "",
  introduction: "",
  password: "",
  startTime: "",
  length: "",
  questionIds: [],
});

const onChange = (dateString: any, date: any) => {
  form.startTime = dateString[0];
  form.length = ((date[1].getTime() - date[0].getTime()) / (1000 * 60)).toFixed(
    0
  );
};
const handleClick = () => {
  Object.keys(form).forEach((key) => {
    form[key] = "";
  });
  visible.value = true;
  if (questionList.value.length === 0) {
    getAllQuestions();
  }
};

const handleClick2 = async (contest: Contest) => {
  visible2.value = true;
  const dateMoment = moment(contest.startTime);
  const updatedMoment = dateMoment.add(contest.length, "minutes");
  const endTime = updatedMoment.format("YYYY-MM-DD HH:mm:ss");
  updateTime.value = [contest.startTime, endTime];

  console.log(updateTime.value);
  if (questionList.value.length === 0) {
    await getAllQuestions();
  }
  form.questionIds = [];
  updateQuestionList.value = [];
  await qt_loadData(contest);
  console.log("hellpo");
  console.log(updateQuestionList.value);
  updateQuestionList.value.forEach((item) => {
    form.questionIds.push(item.questionId + "-" + item.questionVO.title);
  });
  Object.keys(contest).forEach((key) => {
    form[key] = contest[key];
  });
};

const qt_loadData = async (contest: Contest) => {
  const res = await ContestControllerService.getQuestionListUsingGet(
    contest.id as number
  );
  if (res.code === 0) {
    updateQuestionList.value = res.data as any;
  } else {
    message.error("加载失败，" + res.message);
  }
};

const handleCancel = () => {
  visible.value = false;
};
const handleCancel2 = () => {
  visible2.value = false;
};
/**
 * 确认搜索，重新加载数据
 */
const doSubmit = () => {
  // 这里需要重置搜索页号
  searchParams.value = {
    ...searchParams.value,
    current: 1,
  };
};

const loadData = async () => {
  const res = await ContestControllerService.listContestByPageUsingPost(
    searchParams.value
  );
  if (res.code === 0) {
    dataList.value = res.data.records;
    total.value = res.data.total;
  } else {
    message.error("加载失败，" + res.message);
  }
};

const getAllQuestions = async () => {
  const res = await QuestionControllerService.listQuestionByPageUsingPost({
    current: 1,
    pageSize: 100,
  });
  if (res.code === 0) {
    // questionList.value = res.data.records;
    res.data.records.forEach((item) => {
      questionList.value.push(item.id + "-" + item.title);
    });
  } else {
    message.error("加载失败，" + res.message);
  }
};

/**
 * 监听 searchParams 变量，改变时触发页面的重新加载
 */
watchEffect(() => {
  loadData();
});

/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  loadData();
});

// {id: "1", title: "A+ D", content: "新的题目内容", tags: "["二叉树"]", answer: "新的答案", submitNum: 0,…}

const columns = [
  {
    title: "id",
    dataIndex: "id",
    width: 80,
  },
  {
    title: "比赛名",
    dataIndex: "name",
  },
  {
    title: "比赛简介",
    dataIndex: "introduction",
    width: 390,
  },
  {
    title: "比赛密码",
    dataIndex: "password",
    width: 120,
  },
  {
    title: "开始时间",
    dataIndex: "startTime",
    width: 200,
  },
  {
    title: "比赛时间（分钟）",
    dataIndex: "length",
    width: 90,
  },
  // {
  //   title: "作者id",
  //   dataIndex: "writerId",
  // },
  {
    title: "是否完赛",
    dataIndex: "isFinish",
  },
  {
    title: "操作",
    slotName: "optional",
  },
];

const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};

const doDelete = async (contest: Contest) => {
  const res = await ContestControllerService.deleteContestUsingPost({
    ids: [contest.id],
  });
  if (res.code === 0) {
    message.success("删除成功");
    await loadData();
  } else {
    message.error("删除失败");
  }
};

const doBatchDelete = async () => {
  if (selectedKeys.value.length === 0) {
    message.error("未选数据");
    return;
  }
  const res = await ContestControllerService.deleteContestUsingPost({
    ids: selectedKeys.value,
  });
  if (res.code === 0) {
    message.success("删除成功");
    await loadData();
  } else {
    message.error("删除失败");
  }
};

const router = useRouter();
const doAdd = async () => {
  form.questionIds = form.questionIds
    .filter((item) => item.trim() !== "")
    .map((item) => {
      return item.split("-")[0];
    });
  const res = await ContestControllerService.addContestUsingPost(form);
  if (res.code === 0) {
    message.success("添加成功");
    await loadData();
  } else {
    message.error("添加失败，" + res.message);
  }
};
const doUpdate = async (contest: Contest) => {
  form.questionIds = form.questionIds
    .filter((item) => item.trim() !== "")
    .map((item) => {
      return item.split("-")[0];
    });
  const res = await ContestControllerService.updateContestUsingPost(form);
  if (res.code === 0) {
    message.success("修改成功");
    await loadData();
  } else {
    message.error("修改失败，" + res.message);
  }
};
</script>

<style scoped>
#manageContestView {
  max-width: 1800px;
  margin: 0 auto;
}
</style>
